import 'package:flutter/foundation.dart';

/// 展览类型枚举
enum ExhibitionType {
  permanent,  // 常设展览
  temporary,  // 临时展览
  special,    // 特别展览
  virtual,    // 虚拟展览
}

extension ExhibitionTypeExtension on ExhibitionType {
  String get displayName {
    switch (this) {
      case ExhibitionType.permanent:
        return '常设展览';
      case ExhibitionType.temporary:
        return '临时展览';
      case ExhibitionType.special:
        return '特别展览';
      case ExhibitionType.virtual:
        return '虚拟展览';
    }
  }
}

/// 展览状态枚举
enum ExhibitionStatus {
  upcoming,    // 即将开展
  ongoing,     // 展出中
  completed,   // 已结束
  cancelled,   // 已取消
}

/// 展品项目
class ExhibitItem {
  final String id;
  final String name;
  final String description;
  final String imageUrl;
  final String period;      // 年代
  final String origin;      // 产地
  final String material;    // 材质
  final String dimensions;  // 尺寸
  final String significance; // 文化意义
  final List<String> audioGuideUrls; // 语音导览
  final Map<String, dynamic> metadata;

  const ExhibitItem({
    required this.id,
    required this.name,
    required this.description,
    required this.imageUrl,
    this.period = '',
    this.origin = '',
    this.material = '',
    this.dimensions = '',
    this.significance = '',
    this.audioGuideUrls = const [],
    this.metadata = const {},
  });

  factory ExhibitItem.fromJson(Map<String, dynamic> json) {
    return ExhibitItem(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      description: json['description'] ?? '',
      imageUrl: json['image_url'] ?? '',
      period: json['period'] ?? '',
      origin: json['origin'] ?? '',
      material: json['material'] ?? '',
      dimensions: json['dimensions'] ?? '',
      significance: json['significance'] ?? '',
      audioGuideUrls: List<String>.from(json['audio_guide_urls'] ?? []),
      metadata: Map<String, dynamic>.from(json['metadata'] ?? {}),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'image_url': imageUrl,
      'period': period,
      'origin': origin,
      'material': material,
      'dimensions': dimensions,
      'significance': significance,
      'audio_guide_urls': audioGuideUrls,
      'metadata': metadata,
    };
  }
}

/// 展览模型
class Exhibition {
  final String id;
  final String title;
  final String description;
  final DateTime startDate;
  final DateTime endDate;
  final String venue;
  final String address;
  final ExhibitionType type;
  final ExhibitionStatus status;
  final List<ExhibitItem> exhibits;
  final String virtualTourUrl;
  final List<String> images;
  final String curatorName;     // 策展人
  final String curatorInfo;     // 策展人简介
  final double ticketPrice;
  final int maxVisitors;        // 最大参观人数
  final int currentVisitors;    // 当前预约人数
  final String openingHours;    // 开放时间
  final List<String> facilities; // 设施信息
  final Map<String, dynamic> visitingGuidelines; // 参观指南
  final DateTime createdAt;
  final DateTime updatedAt;
  final bool isFeatured;
  final double rating;
  final int reviewCount;
  final List<String> tags;

  const Exhibition({
    required this.id,
    required this.title,
    required this.description,
    required this.startDate,
    required this.endDate,
    required this.venue,
    this.address = '',
    required this.type,
    required this.status,
    this.exhibits = const [],
    this.virtualTourUrl = '',
    this.images = const [],
    this.curatorName = '',
    this.curatorInfo = '',
    this.ticketPrice = 0.0,
    this.maxVisitors = 0,
    this.currentVisitors = 0,
    this.openingHours = '',
    this.facilities = const [],
    this.visitingGuidelines = const {},
    required this.createdAt,
    required this.updatedAt,
    this.isFeatured = false,
    this.rating = 0.0,
    this.reviewCount = 0,
    this.tags = const [],
  });

  factory Exhibition.fromJson(Map<String, dynamic> json) {
    return Exhibition(
      id: json['id'] ?? '',
      title: json['title'] ?? '',
      description: json['description'] ?? '',
      startDate: DateTime.parse(json['start_date'] ?? DateTime.now().toIso8601String()),
      endDate: DateTime.parse(json['end_date'] ?? DateTime.now().toIso8601String()),
      venue: json['venue'] ?? '',
      address: json['address'] ?? '',
      type: ExhibitionType.values.firstWhere(
        (e) => e.name == json['type'],
        orElse: () => ExhibitionType.permanent,
      ),
      status: ExhibitionStatus.values.firstWhere(
        (e) => e.name == json['status'],
        orElse: () => ExhibitionStatus.upcoming,
      ),
      exhibits: (json['exhibits'] as List<dynamic>? ?? [])
          .map((item) => ExhibitItem.fromJson(item))
          .toList(),
      virtualTourUrl: json['virtual_tour_url'] ?? '',
      images: List<String>.from(json['images'] ?? []),
      curatorName: json['curator_name'] ?? '',
      curatorInfo: json['curator_info'] ?? '',
      ticketPrice: (json['ticket_price'] ?? 0.0).toDouble(),
      maxVisitors: json['max_visitors'] ?? 0,
      currentVisitors: json['current_visitors'] ?? 0,
      openingHours: json['opening_hours'] ?? '',
      facilities: List<String>.from(json['facilities'] ?? []),
      visitingGuidelines: Map<String, dynamic>.from(json['visiting_guidelines'] ?? {}),
      createdAt: DateTime.parse(json['created_at'] ?? DateTime.now().toIso8601String()),
      updatedAt: DateTime.parse(json['updated_at'] ?? DateTime.now().toIso8601String()),
      isFeatured: json['is_featured'] ?? false,
      rating: (json['rating'] ?? 0.0).toDouble(),
      reviewCount: json['review_count'] ?? 0,
      tags: List<String>.from(json['tags'] ?? []),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'start_date': startDate.toIso8601String(),
      'end_date': endDate.toIso8601String(),
      'venue': venue,
      'address': address,
      'type': type.name,
      'status': status.name,
      'exhibits': exhibits.map((item) => item.toJson()).toList(),
      'virtual_tour_url': virtualTourUrl,
      'images': images,
      'curator_name': curatorName,
      'curator_info': curatorInfo,
      'ticket_price': ticketPrice,
      'max_visitors': maxVisitors,
      'current_visitors': currentVisitors,
      'opening_hours': openingHours,
      'facilities': facilities,
      'visiting_guidelines': visitingGuidelines,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'is_featured': isFeatured,
      'rating': rating,
      'review_count': reviewCount,
      'tags': tags,
    };
  }

  Exhibition copyWith({
    String? id,
    String? title,
    String? description,
    DateTime? startDate,
    DateTime? endDate,
    String? venue,
    String? address,
    ExhibitionType? type,
    ExhibitionStatus? status,
    List<ExhibitItem>? exhibits,
    String? virtualTourUrl,
    List<String>? images,
    String? curatorName,
    String? curatorInfo,
    double? ticketPrice,
    int? maxVisitors,
    int? currentVisitors,
    String? openingHours,
    List<String>? facilities,
    Map<String, dynamic>? visitingGuidelines,
    DateTime? createdAt,
    DateTime? updatedAt,
    bool? isFeatured,
    double? rating,
    int? reviewCount,
    List<String>? tags,
  }) {
    return Exhibition(
      id: id ?? this.id,
      title: title ?? this.title,
      description: description ?? this.description,
      startDate: startDate ?? this.startDate,
      endDate: endDate ?? this.endDate,
      venue: venue ?? this.venue,
      address: address ?? this.address,
      type: type ?? this.type,
      status: status ?? this.status,
      exhibits: exhibits ?? this.exhibits,
      virtualTourUrl: virtualTourUrl ?? this.virtualTourUrl,
      images: images ?? this.images,
      curatorName: curatorName ?? this.curatorName,
      curatorInfo: curatorInfo ?? this.curatorInfo,
      ticketPrice: ticketPrice ?? this.ticketPrice,
      maxVisitors: maxVisitors ?? this.maxVisitors,
      currentVisitors: currentVisitors ?? this.currentVisitors,
      openingHours: openingHours ?? this.openingHours,
      facilities: facilities ?? this.facilities,
      visitingGuidelines: visitingGuidelines ?? this.visitingGuidelines,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      isFeatured: isFeatured ?? this.isFeatured,
      rating: rating ?? this.rating,
      reviewCount: reviewCount ?? this.reviewCount,
      tags: tags ?? this.tags,
    );
  }

  /// 获取展览状态显示文本
  String get statusText {
    switch (status) {
      case ExhibitionStatus.upcoming:
        return '即将开展';
      case ExhibitionStatus.ongoing:
        return '展出中';
      case ExhibitionStatus.completed:
        return '已结束';
      case ExhibitionStatus.cancelled:
        return '已取消';
    }
  }

  /// 获取展览类型显示文本
  String get typeText {
    switch (type) {
      case ExhibitionType.permanent:
        return '常设展览';
      case ExhibitionType.temporary:
        return '临时展览';
      case ExhibitionType.special:
        return '特别展览';
      case ExhibitionType.virtual:
        return '虚拟展览';
    }
  }

  /// 检查是否可以预约
  bool get canBook {
    return status == ExhibitionStatus.ongoing && 
           currentVisitors < maxVisitors;
  }

  /// 获取剩余名额
  int get remainingSlots {
    return maxVisitors - currentVisitors;
  }

  /// 检查是否已满员
  bool get isFull {
    return currentVisitors >= maxVisitors;
  }

  /// 检查是否有虚拟展厅
  bool get hasVirtualTour {
    return virtualTourUrl.isNotEmpty;
  }

  /// 获取价格（ticketPrice的别名）
  double get price {
    return ticketPrice;
  }

  /// 获取展品列表（exhibits的别名）
  List<ExhibitItem> get items {
    return exhibits;
  }

  /// 获取位置（venue的别名）
  String get location {
    return venue;
  }

  /// 获取参观人数（currentVisitors的别名）
  int get visitCount {
    return currentVisitors;
  }

  /// 获取是否已收藏（默认为false，应由服务管理）
  bool get isBookmarked {
    return false;
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is Exhibition && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'Exhibition{id: $id, title: $title, status: $status, type: $type}';
  }
}

/// 展览筛选器
enum ExhibitionFilter {
  all,         // 全部
  upcoming,    // 即将开展
  ongoing,     // 展出中
  completed,   // 已结束
  ended,       // 已结束（别名）
  traditional, // 传统工艺
  folk,        // 民俗文化
  historical,  // 历史文物
  modern,      // 现代艺术
  interactive, // 互动体验
  featured,    // 精选
  virtual,     // 虚拟展览
  hot,         // 热门
  bookmarked,  // 已收藏
  free,        // 免费
}

/// 展览筛选器扩展
extension ExhibitionFilterExtension on ExhibitionFilter {
  String get displayName {
    switch (this) {
      case ExhibitionFilter.all:
        return '全部';
      case ExhibitionFilter.upcoming:
        return '即将开展';
      case ExhibitionFilter.ongoing:
        return '展出中';
      case ExhibitionFilter.completed:
        return '已结束';
      case ExhibitionFilter.ended:
        return '已结束';
      case ExhibitionFilter.traditional:
        return '传统工艺';
      case ExhibitionFilter.folk:
        return '民俗文化';
      case ExhibitionFilter.historical:
        return '历史文物';
      case ExhibitionFilter.modern:
        return '现代艺术';
      case ExhibitionFilter.interactive:
        return '互动体验';
      case ExhibitionFilter.featured:
        return '精选';
      case ExhibitionFilter.virtual:
        return '虚拟展览';
      case ExhibitionFilter.hot:
        return '热门';
      case ExhibitionFilter.bookmarked:
        return '已收藏';
      case ExhibitionFilter.free:
        return '免费';
    }
  }
}